import { reactive, ref } from 'vue'
import { uploadCSV, getFilterOptions, fetchData } from '../services/api'

export const useDataStore = () => {
  const filterOptions = reactive({
    years: [],
    competitions: [],
    tracks: [],
    provinces: [],
    schools: []
  })

  const tableData = ref([])
  const isLoading = ref(false)

  const refreshFilterOptions = async (params = null) => {
    try {
      const queryString = params ? `?${params.toString()}` : ''
      const options = await getFilterOptions(queryString)
      // Update each array while maintaining reactivity
      filterOptions.years = options.years || []
      filterOptions.competitions = options.competitions || []
      filterOptions.tracks = options.tracks || []
      filterOptions.provinces = options.provinces || []
      filterOptions.schools = options.schools || []
    } catch (error) {
      console.error('Failed to refresh filter options:', error)
    }
  }

  const uploadFile = async (file) => {
    try {
      isLoading.value = true
      await uploadCSV(file)
      await refreshFilterOptions()
    } catch (error) {
      console.error('Upload failed:', error)
      throw error // Pass the detailed error message up
    } finally {
      isLoading.value = false
    }
  }

  const updateData = async (filters) => {
    try {
      isLoading.value = true
      const data = await fetchData(filters)
      tableData.value = data
    } catch (error) {
      console.error('Fetch data failed:', error)
      tableData.value = []
    } finally {
      isLoading.value = false
    }
  }

  return {
    filterOptions,
    tableData,
    isLoading,
    uploadFile,
    updateData,
    refreshFilterOptions
  }
}
